package com.pontodroid;

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class SysInutils {
	
	public static KeyPair ParChaves;
	
	private static String getHexString(byte[] b) {
		String result = "";
		for (int i = 0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}	
	
	public static byte[] getHexStringToByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}	

	public static String encryptBlowfish(String to_encrypt, String strkey) {
		try {
			SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish");
			Cipher cipher = Cipher.getInstance("Blowfish");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return new String(cipher.doFinal(to_encrypt.getBytes()));
		} catch (Exception e) {
			return null;
		}
	}

	public static String decryptBlowfish(String to_decrypt, String strkey) {
		try {
			SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish");
			Cipher cipher = Cipher.getInstance("Blowfish");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decrypted = cipher.doFinal(to_decrypt.getBytes());
			return new String(decrypted);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getHashMD5(String to_hash) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		md.update(to_hash.getBytes());
		byte[] hashMd5 = md.digest();
		return stringHexa(hashMd5);
	}

	private static String stringHexa(byte[] bytes) {
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
			int parteBaixa = bytes[i] & 0xf;
			if (parteAlta == 0)
				s.append('0');
			s.append(Integer.toHexString(parteAlta | parteBaixa));
		}
		return s.toString();
	}

	public static PublicKey StringtoPubKey(String sPbKey) {
		try {
			byte[] keyBytes = getHexStringToByteArray(sPbKey);
			KeyFactory fact = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
			return (PublicKey) fact.generatePublic(x509KeySpec);
		} catch (Exception e) {
			return null;
		}
	}

	public static PrivateKey StringtoPrivKey(String sPrivKey) {
		try {
			byte[] keyBytes = getHexStringToByteArray(sPrivKey);
			KeyFactory fact = KeyFactory.getInstance("RSA");
			KeySpec ks = new PKCS8EncodedKeySpec(keyBytes);
			return (PrivateKey) fact.generatePrivate(ks);
		} catch (Exception e) {
			return null;
		}
	}

	public static String PubKeytoString(PublicKey pPbKey) {
		try {
			byte[] keyBytes = pPbKey.getEncoded();
			return getHexString(keyBytes);
		} catch (Exception e) {
			return null;
		}
	}

	public static String PrivKeytoString(PrivateKey pPrivKey) {
		try {
			byte[] keyBytes = pPrivKey.getEncoded();
			return getHexString(keyBytes);
		} catch (Exception e) {
			return null;
		}
	}

	public static KeyPair GerarParChaves() {

		try {

			KeyPairGenerator gerador = KeyPairGenerator.getInstance("RSA");
			gerador.initialize(1024);
			ParChaves = gerador.generateKeyPair();

			return ParChaves;

		} catch (Exception e) {
			return null;
		}
	}

	private static String Assinar(String pTexto) {

		try {

			FileInputStream arquivoCert = new FileInputStream(
					"PontoKeyStore.jks");
			KeyStore ks = KeyStore.getInstance("JKS");
			Signature sgn = Signature.getInstance("DSA");

			ks.load(arquivoCert, "douglas".toCharArray());
			sgn.initSign((PrivateKey) ks.getKey("PontoDroid",
					"patrick".toCharArray()));
			sgn.update(pTexto.getBytes());
			return sgn.sign().toString();

		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	public static String CriptaDecriptaKey(Key pKey, String pTexto,
			boolean Criptografa) {
		try {

			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			SecureRandom secureRandom = new SecureRandom();
			if (Criptografa){
				cipher.init(Cipher.ENCRYPT_MODE, pKey);				
				return getHexString((cipher.doFinal(pTexto.getBytes())));
			}else{
				byte[] sTexto = getHexStringToByteArray(pTexto);
				cipher.init(Cipher.DECRYPT_MODE, pKey);
				return new String(cipher.doFinal(sTexto));
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	


}
